<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Wyp
 */

namespace App\Modules\Live\Services;


use App\Exceptions\AllValidatorException;
use App\Exceptions\NotFoundException;
use App\Lib\Utilities;
use App\Modules\Live\Criterias\LiveCriteria;
use App\Modules\Live\Criterias\LiveDetailsCriteria;
use App\Modules\Live\Criterias\LiveMemberCriteria;
use App\Modules\Live\Repositories\AuthenticationRepository;
use App\Modules\Live\Repositories\LiveAttentionRepository;
use App\Modules\Live\Repositories\LiveAttentionMemberRepository;
use App\Modules\Live\Repositories\LiveLikeRepository;
use App\Modules\Live\Repositories\LiveRepository;
use App\Modules\Live\Repositories\LiveMemberRepository;
use App\Modules\Live\Repositories\MemberRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use App\Lib\Facades\FLAuth;
use Illuminate\Support\Facades\DB;

class LiveService extends BaseService
{

    private $liveRepository;
    private $liveMemberRepository;
    private $memberRepository;
    private $liveLikeRepository;
    private $liveAttentionRepository;
    private $authenticationRepository;
    private $liveAttentionMemberRepository;


    public function __construct(LiveRepository $liveRepository,
                                LiveMemberRepository $liveMemberRepository,
                                MemberRepository $memberRepository,
                                LiveLikeRepository $liveLikeRepository,
                                LiveAttentionRepository $liveAttentionRepository,
                                AuthenticationRepository $AuthenticationRepository,
                                LiveAttentionMemberRepository $liveAttentionMemberRepository
    )
    {
        $this->liveRepository = $liveRepository;
        $this->liveMemberRepository = $liveMemberRepository;
        $this->memberRepository = $memberRepository;
        $this->liveLikeRepository = $liveLikeRepository;
        $this->liveAttentionRepository = $liveAttentionRepository;
        $this->authenticationRepository = $AuthenticationRepository;
        $this->liveAttentionMemberRepository = $liveAttentionMemberRepository;
    }

    /**
     * 获取直播间信息
     * @param $live_id
     * @return mixed
     * @throws AllValidatorException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getLiveInfo($live_id)
    {
        $live = $this->liveRepository->pushCriteria(new LiveDetailsCriteria($live_id))->first();
        if (!$live) {
            throw new AllValidatorException(['msg' => '直播不存在', 'statusCode' => 400, 'errorCode' => 1404]);
        }
        //点赞数
        $like_num = $this->liveLikeRepository->getLiveLikeNum($live_id);
        $live['like_num'] = $like_num;
        //在线人数
        $menber_num = $this->liveMemberRepository->getMemberNum($live_id);
        $live['member_num'] = $menber_num;
        return $live;
    }

    /**
     * 获取直播数据
     * @param $live_id
     * @return mixed
     * @throws AllValidatorException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getLiveData($live_id)
    {
        $live = $this->liveRepository->findWhere(['id'=>$live_id],['id','user_id','created_at'])->first()->toarray();

        if (!$live) {
            throw new AllValidatorException(['msg' => '直播不存在', 'statusCode' => 400, 'errorCode' => 1404]);
        }
        //点赞数
        $like_num = $this->liveLikeRepository->getLiveLikeNum($live_id);
        $live['like_num'] = $like_num;
        //在线人数
        $member_num = $this->liveMemberRepository->getMemberNumAll($live_id);
        $live['member_num'] = $member_num;
        //新增粉丝
        $attention_num = $this->liveAttentionRepository->getNewAttentionNum($live['user_id'],$live['created_at']);
        $live['attention_num'] = $attention_num;
        //时长
        $start_time = strtotime($live['created_at']);
        $end_time = time();
        $time_diff = $end_time - $start_time;
        $h = intval($time_diff/(60*60));
        $i = intval(($time_diff-$h*60*60)/60);
        $s = intval($time_diff%60);

        $live['times'] = $h.':'.$i.':'.$s;
        return $live;
    }

    public function getStoreId($live_id) {
        $live = $this->liveRepository->findWhere(['id'=>$live_id],['id','store_id'])->first()->toarray();
        return $live;
    }

    /**
     * 获取房间信息
     * @param $live_id
     * @return mixed
     * @throws AllValidatorException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getRoomInfo($live_id)
    {
        //主播信息
        $live = $this->liveRepository->pushCriteria(new LiveCriteria($live_id))->first();
        //用户排名
        $list = $this->liveRepository->getLiveList();
        $num = 0;//未直播排名返回0
        for($i=0;$i<count($list);$i++) {
            if($list[$i]['id'] == $live_id) {
                $num = $i+1;
                continue;
            }
        }
        $live['num'] = $num;
        //点赞数
        $like_num = $this->liveLikeRepository->getLiveLikeNum($live_id);
        $live['like_num'] = $like_num;
        //粉丝数
        $live_array = $live->toarray();
        $attention_num = $this->liveAttentionRepository->getLiveAttentionNum($live_array['user_id']);
        $live['attention_num'] = $attention_num;
        if (!$live) {
            throw new AllValidatorException(['msg' => '直播不存在', 'statusCode' => 400, 'errorCode' => 1404]);
        }
        return $live;
    }

    /**
     * 根据id获取用户昵称
     * @param $member_id
     * @return mixed
     * @throws AllValidatorException
     */
    public function getMemberInfo($member_id)
    {
        $member = $this->memberRepository->getMemberInfo($member_id);
        if (!$member) {
            throw new AllValidatorException(['msg' => '用户不存在', 'statusCode' => 400, 'errorCode' => 1404]);
        }
        return $member;
    }


    /**
     * 创建直播
     * @param $name
     * @param $user_id
     * @param $picture
     * @param $url
     * @param $store_id
     * @param $rtmp
     * @param $flv
     * @return mixed
     * @throws \Exception
     */
    public function createLive($name,$user_id,$picture,$url,$store_id,$rtmp,$flv)
    {
        $live_id_array = $this->liveRepository->getLiveId($user_id)->toarray();
        if($live_id_array) {
            foreach ($live_id_array as $val) {
                $roomID = strval($val['id']);
                $data['GroupId'] = $roomID;
                $data  = json_encode($data);
                $api = new TLSSigAPIv2(env('SDK_APP_ID'),env('PRIVATE_KEY_STRING'));
                $user_sig = $api->genSig('zaoxingshi');
                $url = 'https://console.tim.qq.com/v4/group_open_http_svc/destroy_group?usersig='.$user_sig.'&apn=1&identifier=zaoxingshi&sdkappid='.env('SDK_APP_ID').'&contenttype=json';
                $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                $output = curl_exec($curl);
                curl_close($curl);
                $res = json_decode($output,true);
            }
        }
        //关闭未关闭直播
        DB::table("live")->where('user_id',$user_id)->update(['status'=>0]);
        //创建直播
        $live = $this->liveRepository->createLive($name,$user_id,$picture,$url,$store_id,$rtmp,$flv);

        return $live;

    }

    /**
     * 关闭直播间
     * @param $live_id
     * @return mixed
     * @throws AllValidatorException
     */
    public function editLive($live_id)
    {
        //更新数据
        $data['status'] = 0;
        $data['updated_at'] = date('Y-m-d H:i:s');
        return $this->liveRepository->editLive($live_id,$data);
    }


    /**
     * 获取在线用户列表
     * @param $live_id
     * @param $pageSize
     * @param $page
     * @return array
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getLiveMemberListPage($live_id,$pageSize,$page)
    {
        $member_list = $this->liveMemberRepository->pushCriteria(new LiveMemberCriteria($live_id))->paginate($pageSize, ['*'], 'paginate',$page)->toarray();

        if($member_list['data']) {
            foreach ($member_list['data'] as $key=>&$val) {
                $coin = DB::table("gift_send")->selectRaw('sum(money) as coin')->where('member_id',$val['id'])->where('live_id',$live_id)->first();
                if($coin) {
                    $val['coin'] = intval($coin->coin);
                }else {
                    $val['coin'] = 0;
                }
                $attention = $this->liveAttentionMemberRepository->getAttention($val['id'],FLAuth::id());
                if($attention) {
                    $val['attention'] = 1;
                }else {
                    $val['attention'] = 0;
                }
            }
        }

        //处理分页数据
        $activity_list = Utilities::dealPage($member_list);
        return $activity_list;
    }

    /**
     * 点赞
     * @param $member_id
     * @param $live_id
     * @return mixed
     * @throws AllValidatorException
     */
    public function addLiveLike($member_id,$live_id)
    {
        $liveLike = $this->liveLikeRepository->createLiveLike($member_id,$live_id);
        return $liveLike;
    }

    /**
     * 取消点赞
     * @param $member_id
     * @param $live_id
     * @return mixed
     * @throws AllValidatorException
     */
    public function updateLiveLike($member_id,$live_id)
    {
        $livelike = $this->liveLikeRepository->editLiveLike($member_id,$live_id);
        return $livelike;
    }

    /**
     * 关注
     * @param $member_id
     * @param $user_id
     * @return mixed
     * @throws AllValidatorException
     */
    public function addLiveAttention($member_id,$user_id)
    {
        $liveAttention = $this->liveAttentionMemberRepository->createLiveAttention($member_id,$user_id);
        return $liveAttention;
    }

    /**
     * 取消关注
     * @param $member_id
     * @param $user_id
     * @return mixed
     * @throws AllValidatorException
     */
    public function updateLiveAttention($member_id,$user_id)
    {
        $liveAttention = $this->liveAttentionMemberRepository->editLiveAttention($member_id,$user_id);
        return $liveAttention;
    }

    /**
     * 主播认证
     * @param $identity
     * @param $user_id
     * @param $name
     * @return mixed
     */
    public function addAuthentication($identity,$user_id,$name)
    {
        $authentication = $this->authenticationRepository->createAuthentication($user_id,$name,$identity);
        return $authentication;
    }

    /**
     * 上热门
     * @param $live_id
     * @param $user_id
     * @return mixed
     * @throws AllValidatorException
     */
    public function addHot($live_id)
    {
        $user = DB::table('user')->find(FLAuth::id());
        if($user->coin < 100) {
            throw new AllValidatorException(['msg' => '县令币不足', 'statusCode' => 400, 'errorCode' => 1404]);
        }else {
            $data_user['coin'] = $user->coin-100;
            DB::table('user')->where(['id'=>FLAuth::id()])->update($data_user);
        }
        $data['is_hot'] = 1;
        $live = $this->liveRepository->editLive($live_id,$data);
        return $live;
    }

    /**
     * 获取主播认证
     * @param $user_id
     * @return mixed
     */
    public function getAuthentication($user_id)
    {
        $authentication = $this->authenticationRepository->getAuthentication($user_id);
        return $authentication;
    }

}
